/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.service.syndication;

import java.util.Collection;

import net.martinimix.dao.syndication.SyndicationFeedDao;
import net.martinimix.domain.syndication.SyndicationFeed;

/**
 * Provides a Martini Mix syndication service.
 * 
 * @author Scott Rossillo
 *
 */
public class MartiniMixSyndicationService implements SyndicationService {

	private SyndicationFeedDao syndicationFeedDao;
	
	
	/**
	 * Creates a uniform resource name (URN) for the given feed.
	 * 
	 * The returned URN is derived from the given <code>feed</code>'s title
	 * such that all all non-alphanumeric characters are replaced with dashes
	 * and alphabetic characters are converted to lower case.
	 * 
	 * @param feed the <code>SyndicationFeed</code> for which a URN should
	 * be created; may not be <code>null</code>
	 * 
	 * @return a URN for the given <code>feed</code> or <code>null</code> if the
	 * given <code>feed</code>'s title is <code>null</code> 
	 */
	protected String createUrn(SyndicationFeed feed) {
		
		if(feed == null) {
			throw new IllegalArgumentException("[SyndicationFeed] cannot be null!");
		}
		
		if(feed.getTitle() == null) {
			return null;
		}
		
		//String urn = 
		
		
		return feed.getTitle().toLowerCase().trim().replaceAll("\\W", "-");
	}
	
	/* (non-Javadoc)
	 * @see net.martinimix.service.syndication.SyndicationService#findFeed(long)
	 */
	public SyndicationFeed findFeed(long id) {
		return syndicationFeedDao.findFeed(id);
	}

	/* (non-Javadoc)
	 * @see net.martinimix.service.syndication.SyndicationService#getAllFeeds()
	 */
	public Collection getAllFeeds() {
		
		return syndicationFeedDao.getAllFeeds();
	}

	/* (non-Javadoc)
	 * @see net.martinimix.service.syndication.SyndicationService#save(net.martinimix.domain.syndication.SyndicationFeed)
	 */
	public void save(SyndicationFeed feed) {
		
		if(feed.getUrn() == null) {
			feed.setUrn(createUrn(feed));
		}
		
		syndicationFeedDao.save(feed);
	}

	/**
	 * @param syndicationFeedDao the syndicationFeedDao to set
	 */
	public void setSyndicationFeedDao(SyndicationFeedDao syndicationFeedDao) {
		this.syndicationFeedDao = syndicationFeedDao;
	}

}
